package com.xxx.landlord.client.controller;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class GameController {

    @FXML
    private AnchorPane anchorPane;

    @FXML
    private Button backBtn;

    @FXML
    private Button notPlayBtn;

    @FXML
    private Button notRobBtn;  // 不抢按钮

    @FXML
    private Button playCardBtn;

    @FXML
    private Button robBtn;  // 抢地主按钮

    @FXML
    private StackPane showLandlordCard;  // 底牌区域

    @FXML
    private StackPane showLeftCard;  // 左玩家牌区

    @FXML
    private StackPane showMyCard;  // 我的牌区

    @FXML
    private StackPane showRightCard;  // 右玩家牌区

    // 新增抢地主相关组件和变量
    private Text gameNotice;  // 游戏通知文本
    private boolean isLandlord = false;
    private String currentLandlord;
    private List<String> myCards = new ArrayList<>();
    private List<String> landlordCards = new ArrayList<>();  // 底牌

    // 网络相关
    private Socket socket;
    private ObjectInputStream in;
    private ObjectOutputStream out;

    // 抢地主流程控制
    private CountDownLatch robLatch;
    private String robResult = "";

    @FXML
    public void initialize() {
        // 初始化游戏通知文本
        gameNotice = new Text("游戏准备中...");
        gameNotice.setLayoutX(200);
        gameNotice.setLayoutY(50);
        anchorPane.getChildren().add(gameNotice);

        // 初始化底牌区域
        initLandlordCardArea();
    }

    /**
     * 初始化底牌显示区域
     */
    private void initLandlordCardArea() {
        showLandlordCard.setStyle("-fx-background-color: #8B4513; -fx-background-radius: 5;");
        showLandlordCard.setPrefSize(200, 100);
    }

    /**
     * 处理退出按钮点击事件
     */
    @FXML
    void handleBack(ActionEvent event) {
        System.out.println("点击了退出按钮");
        // 这里添加退出游戏的逻辑，例如：
        // 关闭当前窗口
        // 断开网络连接
        // 返回主菜单等
    }

    /**
     * 抢地主主流程
     */
    public boolean startRobLandlord() throws IOException, InterruptedException {
        Platform.runLater(() -> gameNotice.setText("开始抢地主"));

        int passCount = 0;
        boolean robSuccess = false;

        // 三轮抢地主
        for (int i = 0; i < 3; i++) {
            // 等待服务器消息
            String serverMsg = getServerMessage();

            if (serverMsg.equals("轮到你抢地主")) {
                Platform.runLater(() -> {
                    gameNotice.setText("轮到你抢地主，请选择抢或不抢");
                    // 显示抢地主按钮
                    robBtn.setVisible(true);
                    notRobBtn.setVisible(true);
                });

                // 等待用户选择
                robLatch = new CountDownLatch(1);
                robLatch.await();  // 阻塞等待用户操作

                // 发送用户选择
                sendMessage(robResult);

                if (robResult.equals("不抢")) {
                    passCount++;
                } else {
                    // 抢地主
                    robSuccess = true;
                }

                // 隐藏按钮
                Platform.runLater(() -> {
                    robBtn.setVisible(false);
                    notRobBtn.setVisible(false);
                });
            } else {
                // 显示其他玩家操作
                Platform.runLater(() -> gameNotice.setText(serverMsg));

                if (serverMsg.contains("不抢")) {
                    passCount++;
                }
            }
        }

        // 处理抢地主结果
        if (passCount == 3) {
            // 所有人都不抢，重新发牌
            Platform.runLater(() -> gameNotice.setText("所有人都不抢地主，重新发牌"));
            return false;
        }

        // 获取最终地主信息
        String landlordInfo = getServerMessage();
        if (landlordInfo.equals("你成为地主")) {
            isLandlord = true;
            currentLandlord = "你";
            // 获取三张底牌
            getLandlordCards();
            Platform.runLater(() -> {
                gameNotice.setText("你成为地主！");
                showLandlordCards();  // 显示底牌
            });
        } else {
            currentLandlord = landlordInfo;
            Platform.runLater(() -> gameNotice.setText(landlordInfo + "成为地主"));
        }

        return true;
    }

    /**
     * 获取底牌
     */
    private void getLandlordCards() throws IOException {
        landlordCards.clear();
        for (int i = 0; i < 3; i++) {
            String card = getServerMessage();
            landlordCards.add(card);
            myCards.add(card);  // 地主获得底牌
        }
    }

    /**
     * 显示底牌
     */
    private void showLandlordCards() {
        // 清空现有内容
        showLandlordCard.getChildren().clear();

        // 显示三张底牌
        for (int i = 0; i < landlordCards.size(); i++) {
            ImageView cardImg = new ImageView(new Image("/cards/" + landlordCards.get(i) + ".png"));
            cardImg.setFitWidth(60);
            cardImg.setFitHeight(80);
            cardImg.setLayoutX(i * 70 + 10);  // 横向排列
            cardImg.setLayoutY(10);
            showLandlordCard.getChildren().add(cardImg);
        }
    }

    /**
     * 点击抢地主按钮
     */
    @FXML
    void handleRobLandlord(ActionEvent event) {
        System.out.println("点击了抢地主");
        robResult = "抢";
        if (robLatch != null) {
            robLatch.countDown();  // 解除阻塞
        }
    }

    /**
     * 点击不抢按钮
     */
    @FXML
    void handleNotRob(ActionEvent event) {
        System.out.println("点击了不抢");
        robResult = "不抢";
        if (robLatch != null) {
            robLatch.countDown();  // 解除阻塞
        }
    }

    // 网络通信方法
    private String getServerMessage() throws IOException {
        try {
            return (String) in.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException("读取消息失败", e);
        }
    }

    private void sendMessage(String message) throws IOException {
        out.writeObject(message);
        out.flush();
    }

    // Setter方法
    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public void setIn(ObjectInputStream in) {
        this.in = in;
    }

    public void setOut(ObjectOutputStream out) {
        this.out = out;
    }

    public void setMyCards(List<String> cards) {
        this.myCards = cards;
    }

    // Getter方法
    public boolean isLandlord() {
        return isLandlord;
    }

    public String getCurrentLandlord() {
        return currentLandlord;
    }
}
